import { resolve } from 'path';
import { defineConfig, loadEnv } from 'vite';

import vue from '@vitejs/plugin-vue';
import { VitePWA } from 'vite-plugin-pwa';
import compression from 'vite-plugin-compression';
import { createStyleImportPlugin, VantResolve, AntdResolve } from 'vite-plugin-style-import';

const outDir = '../web/wwwroot';
const targetUrl = 'http://localhost:8881/';

// https://vitejs.dev/config/
export default ({ mode }) => defineConfig({
  base: loadEnv(mode, process.cwd()).VITE_Base,
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true
      }
    }
  },
  plugins: [
    vue(),
    createStyleImportPlugin({
      resolves: [AntdResolve, VantResolve],
      libs: [
        {
          libraryName: 'ant-design-vue',
          esModule: true,
          resolveStyle: name => `ant-design-vue/es/${name}/style/css`
        },
        {
          libraryName: 'vant',
          esModule: true,
          resolveStyle: name => `../es/${name}/style`
        }
      ]
    }),
    compression(),
    VitePWA({
      base: '/',
      registerType: 'autoUpdate',
      filename: 'sw.web.js',
      injectRegister: 'inline',
      manifestFilename: 'manifest.webmainfest',
      manifest: {
        id: '/',
        name: '个人帮助系统',
        short_name: 'PHS',
        icons: [{
          src: '/phs.png',
          sizes: '144x144',
          type: 'image/png'
        }],
        start_url: '/'
      }
    })
  ],
  resolve: {
    alias: {
      '@': resolve(__dirname, './portal'),
      '~': resolve(__dirname, './mobile')
    }
  },
  server: {
    open: '/portal.html',
    host: '0.0.0.0',
    port: 7100,
    cors: true,
    proxy: {
      '^/api': { ws: true, changeOrigin: true, target: targetUrl },
      '^/.+/api': { ws: true, changeOrigin: true, target: targetUrl },
      '^/docs': { ws: true, changeOrigin: true, target: targetUrl },
      '^/styles': { ws: true, changeOrigin: true, target: targetUrl },
      '^/scripts': { ws: true, changeOrigin: true, target: targetUrl },
      '^/swagger': { ws: true, changeOrigin: true, target: targetUrl }
    }
  },
  build: {
    target: 'es6',
    outDir: outDir,
    minify: 'esbuild',
    emptyOutDir: true,
    rollupOptions: {
      input: {
        portal: resolve(__dirname, 'portal.html'),
        mobile: resolve(__dirname, 'mobile.html')
      }
    },
    terserOptions: {
      compress: {
        keep_infinity: true,
        // Used to delete console in production environment
        drop_console: true
      }
    },
    // Turning off brotliSize display can slightly reduce packaging time
    brotliSize: false,
    chunkSizeWarningLimit: 2000
  }
});
